package murraco.security;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import murraco.model.User;
import murraco.repository.UserRepository;

@Service
public class MyUserDetailService implements UserDetailsService {

  @Autowired
  private UserRepository userRepository;

  @Override
  public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
    final User user = userRepository.findByLoginCode(username);

    if (user == null) {
      throw new UsernameNotFoundException("User '" + username + "' not found");
    }
    MyUserDetail userDetail = new MyUserDetail();

    userDetail.setUsername(user.getLoginCode());
    userDetail.setUserId(user.getLoginCode());
    userDetail.setPassword(user.getPassword());
    userDetail.setAuthorities(user.getRoles());
    return userDetail;
  }

}
